package com.recommend.controller.admin;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.util.Date;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.recommend.domain.MovieDomain;
import com.recommend.service.MovieService;
import org.springframework.web.multipart.MultipartFile;

/**
 * Created by lw.
 */
@Controller
@RequestMapping("/admin/movie")
public class MovieController {
    private final static Logger logger = LoggerFactory.getLogger(LoginController.class);

    @Autowired
    private MovieService movieService;

    private MovieDomain transfer(MovieDomain movieDomain){
        if(null == movieDomain.getAction()){
            movieDomain.setAction(0);
        }
        if(null == movieDomain.getAdventure()){
            movieDomain.setAdventure(0);
        }
        if(null == movieDomain.getAnimation()){
            movieDomain.setAnimation(0);
        }
        if(null == movieDomain.getChildren()){
            movieDomain.setChildren(0);
        }
        if(null == movieDomain.getComedy()){
            movieDomain.setComedy(0);
        }
        if(null == movieDomain.getCrime()){
            movieDomain.setCrime(0);
        }
        if(null == movieDomain.getFantasy()){
            movieDomain.setFantasy(0);
        }
        if(null == movieDomain.getRomance()){
            movieDomain.setRomance(0);
        }
        return movieDomain;
    }

    @RequestMapping(value = "/searchMovie", method = RequestMethod.POST)
    @ResponseBody
    public List<MovieDomain> searchMovie(MovieDomain movieDomain){
        logger.info("=======================search movie title:{}", movieDomain.getMovieTitle());
        return movieService.searchMovie(movieDomain);
    }

    @RequestMapping(value = "/searchMovieById", method = RequestMethod.POST)
    @ResponseBody
    public MovieDomain searchMovieById(@RequestParam("movieId") int movieId){
        logger.info("=======================search movie MovieId:{}", movieId);
        return movieService.getMovie(movieId);
    }

    @RequestMapping(value = "/getAllMovies", method = RequestMethod.POST)
    @ResponseBody
    public List<MovieDomain> getAllMovies(){
        logger.info("==============================get all movies");
         return movieService.getAllMovie();
    }

    @RequestMapping(value = "/addMovie", method = RequestMethod.POST)
    @ResponseBody
    public int addMovie(MovieDomain movieDomain){
        logger.info("==============================add movie");
        logger.info("====movie_title:{}, time:{}, url:{}===", movieDomain.getMovieTitle(), movieDomain.getReleaseDate(), movieDomain.getUrl());
        return movieService.addMovie(movieDomain);
    }

    @RequestMapping(value = "/updateImage", method = RequestMethod.POST)
    @ResponseBody
    public String updateImage(@RequestParam("imageMovieId") int imageMovieId,
                           @RequestParam("image") MultipartFile file){
        MovieDomain movieDomain = new MovieDomain();
        movieDomain.setMovieId(imageMovieId);
        logger.info("==============================update image");
        if (!file.isEmpty()) {
            try {
                String orgName = file.getOriginalFilename();
                Date date = new Date();
                String fileName = "F:\\project\\Movie\\target\\classes\\static\\img\\" + date.getTime() + orgName;
                byte[] bytes = file.getBytes();
                BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(new File(fileName)));
                stream.write(bytes);
                stream.close();
                String storageFile = "../img/" + date.getTime() + orgName;
                movieDomain.setImage(storageFile);
                movieService.updateMovie(movieDomain);
                return "success! <a href='/admin/movieManage.html'>return</a>";
            } catch (Exception e) {
                logger.info("You failed to upload image => " + e.getMessage());
                return "failed";
            }
        } else {
            return "failed";
        }
    }

    @RequestMapping(value = "/updateMovie", method = RequestMethod.POST)
    @ResponseBody
    public int updateMovie(MovieDomain movieDomain){
        logger.info("==============================update movie");
        return movieService.updateMovie(transfer(movieDomain));
    }


    @RequestMapping(value="/upload1", method=RequestMethod.GET)
    public @ResponseBody String provideUploadInfo() {
        return "You can upload a file by posting to this same URL.";
    }

    //
    @RequestMapping(value="/upload", method=RequestMethod.POST)
    public @ResponseBody String handleFileUpload(@RequestParam("imageMovieId") String imageMovieId,@RequestParam("image") MultipartFile file){
        logger.info("==================id:{}", imageMovieId);
        if (!file.isEmpty()) {
            try {
                String orgName = file.getOriginalFilename();
                Date date = new Date();
                String fileName = "F:\\img\\" + date.getTime() + orgName;
                byte[] bytes = file.getBytes();
                BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(new File(fileName)));
                stream.write(bytes);
                stream.close();
                return  fileName;
            } catch (Exception e) {
                return "You failed to upload  => " + e.getMessage();
            }
        } else {
            return "You failed to upload  because the file was empty.";
        }
    }
}
